package cn.xianshu.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre"; // 前置拦截
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行run方法 做出判断
        // 1.获取请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 2.获取请求的URL
        String requestURI = request.getRequestURI();
        // 3.判断是否为login、register
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        return true;


    }

    @Override
    public Object run() throws ZuulException {
        // 核心方法做登录检查
        // 1.拿到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 2.拿到请求头的Token
        String token = request.getHeader("token");
        // 3.如果token为空  视为未登录
        if (StringUtils.isEmpty(token)){
            // 3.1返回一个请求错误的信息  由于返回请求必须为json所以需要转换成json
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("application/json;charset = utf-8");
                response.getWriter().write("请登录!");
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 3.2阻止继续往后执行
            currentContext.setSendZuulResponse(false);
        }
        // 4.token不为空就返回null 放行
        return null;
    }
}
